import { ServerContext } from '../index';
import { NextHandleFunction } from "connect";
import path from "path";
import { pathExists, readFile } from "fs-extra";
export function indexHtmlMiddware(serverContext: ServerContext): NextHandleFunction {
  return async (req, res, next) => {
    if (req.url === "/") {
      const { root } = serverContext;
      const indexHtmlPath = path.join(root, "index.html");
      // console.log("初始路径", indexHtmlPath)
      if (await pathExists(indexHtmlPath)) {
        const rawHtml = await readFile(indexHtmlPath, "utf-8");
        let html = rawHtml
        // console.log(html)
        for (const plugin of serverContext.plugins) {
          if (plugin.transformIndexHtml) {
            html = await plugin.transformIndexHtml(html)
          }
        }
        res.statusCode = 200;
        res.setHeader('Content-Type', "text/html")
        return res.end(html)
      }
    }
    return next()
  }
}